package com.solution.common.utils.httpsclient;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

import com.solution.common.utils.Global;

/**
 * X.509证书验证管理
 * @author llp
 * @date 2017/5/6 11:36
 */
public class MyX509TrustManager implements X509TrustManager {
	private Certificate cert = null;
	public MyX509TrustManager() {
		try {
			// 加载证书安装
			FileInputStream fis = new FileInputStream(Global.getConfig("cerPath"));
			BufferedInputStream bis = new BufferedInputStream(fis);
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			while (bis.available() > 0) {
				cert = cf.generateCertificate(bis);
			}
			bis.close();
		} catch (CertificateException | IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		for (X509Certificate cert : chain) {
			if (cert.toString().equals(this.cert.toString()))
				return;
		}
		// 如果服务端证书和本地证书不一致，则抛出异常
		throw new CertificateException("certificate is illegal");
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		return new X509Certificate[] { (X509Certificate) cert};
	}

}